<!-- src/views/LogSearch.vue -->
<template>
  <Section padding="0 2rem 0 0rem">
    <GapedColumn gap="middle">
      <!-- Page Header -->
      <page-header :title="pageTitle" icon="search">
        <template #extra>
          <!-- Additional header content if needed -->
        </template>
      </page-header>

      <!-- Search Form -->
      <log-search-form
        :tableName="currentTable.name"
        :fields="tableFields"
        @search="handleSearch"
        @reset="handleReset"
      />

      <!-- Results Table -->
      <log-search-results
        :tableName="currentTable.name"
        :fields="tableFields"
        :data="logData"
        :loading="apiStore.apiStates.searchLogs.loading"
        :total="total"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @column-changed="handleColumnChanged"
        @view-click="showDetail"
      />
    </GapedColumn>

    <!-- Detail Dialog -->
    <el-dialog v-model="dialogVisible" :width="dialogWidth">
      <log-detail v-if="dialogVisible" :log-data="selectedLog" />
    </el-dialog>
  </Section>
</template>

<script setup lang="ts">
import { map } from 'lodash'
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import PageHeader from '@/components/layout/PageHeader.vue'
import LogSearchForm from '@/components/logSearch/LogSearchForm.vue'
import LogSearchResults from '@/components/logSearch/LogSearchResults.vue'
import LogDetail from '@/components/logSearch/LogDetail.vue'
import useApi from '@/core/apiStore'
import { Section, GapedColumn } from '@/core/components'
import type {
  SearchParam,
  TableField,
  Table,
} from '@/components/logSearch/types'
import { ElMessage } from 'element-plus'

const pageSize = 10
const apiStore = useApi()
const route = useRoute()

const currentTable = ref<Table | null>(null)
const tableFields = computed<Array<TableField>>(() => {
  return currentTable.value?.fields || []
})

const pageTitle = computed(() => {
  return `日志检索 - ${route.params.tableName}`
})

// 从URL参数获取tableName并设置当前表格
onMounted(() => {
  updateCurrentTable()
})

// 合并后的watch逻辑
watch(
  () => [apiStore.apiStates.getTables.data, route.params.tableName],
  ([tableData, tableName]) => {
    if (tableData && tableName) {
      currentTable.value =
        tableData.tables.find(table => table.name === tableName) || null
    }
  },
  { immediate: true }
)

const logData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const selectedLog = ref(null)
const columnNames = ref([])

const dialogWidth = computed(() => {
  return `${window.innerWidth * 0.9}px`
})

const searchParamRef = ref({})

const updateCurrentTable = () => {
  const tableName = route.params.tableName as string
  const tableData = apiStore.apiStates.getTables.data
  if (tableName && tableData) {
    currentTable.value =
      tableData.tables.find(table => table.name === tableName) || null
  }
}

const handlePageChange = async (pageNum: number) => {
  const result = await apiStore.searchLogs({
    ...searchParamRef.value,
    page_info: {
      ...searchParamRef.value?.page_info,
      index: pageNum - 1,
    },
  })
  const { data, total: totalVal = 0 } = result
  total.value = totalVal
  logData.value = data
}

const handleColumnChanged = (columns: Array<TableField>) => {
  columnNames.value = map(columns, 'name')
}

const handleSearch = async (params: Array<SearchParam>) => {
  console.log('search-param', params)

  // 检查params中undefined值
  const invalidParams = params.filter(param => param.value === undefined)
  if (invalidParams.length > 0) {
    const fieldNames = invalidParams.map(param => param.name).join(', ')
    ElMessage.warning(`以下字段未设置值: ${fieldNames}`)
    return
  }

  const queryParams = {
    index: currentTable.value?.name || 'api_logs',
    params,
    fields: columnNames.value,
    page_info: {
      index: 0,
      size: pageSize,
    },
  }
  searchParamRef.value = queryParams
  const result = await apiStore.searchLogs(queryParams)
  const { data, total: totalVal = 0 } = result
  total.value = totalVal
  logData.value = data
}

const handleReset = () => {
  console.log('Reset search form')
}

const showDetail = (log: any) => {
  console.log('show-log', log)
  selectedLog.value = log
  dialogVisible.value = true
}
</script>
